import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
import numpy as np
from face_lib import  filter_unvisible_faces
from load_model import   load_faces
from key_rotation_in_pygame import get_3_axises_rotation
from rotation_transformation_around_word import rotate_3_axises_around_the_world

# 初始化 Pygame
pygame.init()

# 设置显示模式并创建窗口
display = (800, 600)
pygame.display.set_mode(display, DOUBLEBUF|OPENGL)
clock = pygame.time.Clock()

# 设置透视投影
gluPerspective(45, (display[0]/display[1]), 0.1, 50.0)

# 移动相机位置
glTranslatef(0, 0.0, -5)

faces = load_faces()




def drawTriAngles(triAngleFace,color):
    # 绘制一个简单的三角形

    #vx,vy,vz = triAngleFace
    r,g,b,a=color
    glBegin(GL_TRIANGLES)
    for v in triAngleFace:

        glVertex3fv(v)
        glColor4fv((r/255,g/255,b/255,a/255))
   
    
    glEnd()

dt = 0

# 主循环
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

    # 清空屏幕和深度缓冲
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)

    rotation_degree_x,rotation_degree_y,rotation_degree_z=get_3_axises_rotation(dt)

    # 把模型绕世界坐标轴进行旋转
    rotate = rotate_3_axises_around_the_world(rotation_degree_x,rotation_degree_y,rotation_degree_z)

    # 获取可见多边形的坐标（及其颜色）
    polygones_coordinates = filter_unvisible_faces([rotate(face) for face in faces])

    # 绕世界坐标系的 Y 轴旋转
    # glRotatef(1, 0, 1, 0)

    for visible_face,normal_vector,color in polygones_coordinates:

        drawTriAngles(visible_face,color)


    # 根据鼠标位置旋转相机
    if pygame.mouse.get_pressed()[0]:
        x, y = pygame.mouse.get_rel()
        glRotatef(x, 0, 1, 0)
        glRotatef(y, 1, 0, 0)

    pygame.display.flip()

    # limits FPS to 60
    # dt is delta time in seconds since last frame, used for framerate-
    # independent physics.
    dt = clock.tick(60) / 1000
